package com.yellow.userservice.controller;

import com.qiniu.common.QiniuException;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * @author: hy
 * @create: 2024-03-31
 */
/**
 * controller for handling Qiniu cloud storage operations.
 * Provides an endpoint to generate an upload token for Qiniu cloud storage.
 */
@Slf4j
@RestController
@CrossOrigin("*")
public class QiniuController {

    // Injects the Qiniu access key from application properties.
    @Value("${qiniu.accessKey}")
    private String accessKey;

    // Injects the Qiniu secret key from application properties.
    @Value("${qiniu.secretKey}")
    private String secretKey;

    // Injects the Qiniu bucket name from application properties.
    @Value("${qiniu.bucket}")
    private String bucket;

    /**
     * Generates and returns an upload token for Qiniu cloud storage.
     * The token includes a custom return body policy.
     *
     * @return A String representing the upload token.
     */
    @GetMapping("/getUploadToken")
    public String getUploadToken() {
        // Creates an Auth instance using the provided access and secret keys.
        Auth auth = Auth.create(accessKey, secretKey);
        // Defines the return body policy for the upload token.
        StringMap putPolicy = new StringMap();
        putPolicy.put("returnBody", "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"bucket\":\"$(bucket)\",\"name\":\"$(x:name)\"}");
        // Generates the upload token with a specified bucket, no key, a 3600-second expiration, and the defined policy.
        String upToken = auth.uploadToken(bucket, null, 3600, putPolicy);
        // Logs the generated upload token.
        log.info(upToken);
        return upToken;
    }

    /**
     * Deletes a file from Qiniu cloud storage.
     *
     * @param key The key (filename) of the file to delete.
     * @return ResponseEntity with a success or error message.
     */
    @DeleteMapping("/deleteQiniuFile")
    public ResponseEntity<String> deleteFile(@RequestParam String key) {
        try {
            // Create an Auth instance
            Auth auth = Auth.create(accessKey, secretKey);

            // Create a Configuration instance with the appropriate region
            // Note: You may need to change the region based on your bucket's location
            Configuration cfg = new Configuration(Region.autoRegion());

            // Create a BucketManager instance
            BucketManager bucketManager = new BucketManager(auth, cfg);

            // Delete the file
            bucketManager.delete(bucket, key);

            log.info("Successfully deleted file with key: {}", key);
            return ResponseEntity.ok("File deleted successfully");
        } catch (QiniuException ex) {
            log.error("Failed to delete file with key: {}", key, ex);
            return ResponseEntity.status(ex.code()).body("Failed to delete file: " + ex.response.toString());
        } catch (Exception ex) {
            log.error("Unexpected error when deleting file with key: {}", key, ex);
            return ResponseEntity.status(500).body("Unexpected error: " + ex.getMessage());
        }
    }
}